<?php
/**
 * 	app转账接口
 *  =============================
 * 	后台父类
 * 	=============================
 *	Author: 褚天恩
 *  Date: 2017-10-09
 * @author Administrator
 *
 */
namespace app\wallet\controller;
use Think\Db;
use think\Cache;
class Transfer extends Base {
	
    //空操作
    public function _initialize(){
        parent::_initialize();
    }
    /**
     * 转账方法
     */
    public function transfer_add(){
//     	$data['data'] = array('user_id'=>'','token'=>'');
//     	$data['code']= -9;
//     	$data['msg']= '该服务已暂停';
//     	return json($data);
    	$user_id = Base::$member['user_id'];
    	$email = input('email');//获取转账的用户
    	$pwd = input("paypwd");//获取二级密码
    	$money = input("money");//获取转的金额 默认是0
    	$type = intval(input('type'));//获取转账的币种
    	$name = input('name');//获取姓名
    	$token = input('token');
    	$pay_member = Db::name('Users')->where(array('userId'=>$user_id))->find();
    	if(empty($email)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -1;
    		$data['msg']= '请填写用户名';
    		return json($data);
    	}
    	if(empty($pwd)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -2;
    		$data['msg']= '请填写二级密码';
    		return json($data);
    	}
    	
    	if($pay_member['payPwd']!=md5($pwd)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -3;
    		$data['msg']= '交易密码错误';
    		return json($data);
    	}
    	if(empty($money)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -5;
    		$data['msg']= '请输入转账金额';
    		return json($data);
    	}
    	if(empty($name)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -7;
    		$data['msg']= '请输入真实姓名';
    		return json($data);
    	}
    	$get_member = M("Users")->where(array('loginName'=>$email))->find();
    	if(empty($get_member)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -8;
    		$data['msg']= '无效用户';
    		return json($data);
    	}
    	$list = db('App_member_relation')->where(array('member_id'=>$get_member['userId']))->find();
    	
    	$list_name = $list['name'];
    	if($name!=$list_name){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -10;
    		$data['msg']= '真实姓名错误';
    		return json($data);
    	}
    	
    	if(!is_int($type) || $type > 4){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -6;
    		$data['msg']= '积分无效';
    		return json($data);
    	}
    	$finance = new \FinanceApi();
    	$one = M('app_member_account')->field('account_type_'.$type)->where(array('member_id'=>$user_id))->find();
    	$account_type_one = M('app_account_type')->where(array('id'=>$type))->find();//获取币种的信息
    	//判断转账上限
    	$limit_type = $account_type_one['limit_type'];
    	if($limit_type == 2){
    		$db = $finance->judgeNowMonthFinance();
    		$where['finance_type'] = 3;
    		$where['member_id'] = $user_id;
    		$old_money = DB::name($db)->where($where)->sum('money');
    		$all_money = $old_money +$money;
    	}else{
    		$all_money = $money;
    	}
    	//判断转账上限
    	$top = $account_type_one['limit_transfer_money'];
    	if($all_money > $top){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -6;
    		$data['msg']= '超出转账限额';
    		return json($data);
    	}    	
    	
    	//账户信息
    	//获取要转账的币种的余额
    	//获取所有的币种余额
    	
    	$bili = $account_type_one['transfer_fee_bili'];
    	$fee = $money*$bili*0.01;
    	$all_money = $money+$fee;
    	if($one['account_type_'.$type]<$all_money){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -6;
    		$data['msg']= $account_type_one['name']."不足";
    		return json($data);
    	}
    	//账户余额操作
    	$re[]=M("App_member_account")->where(['member_id'=>$user_id])->setDec('account_type_'.$type,$all_money);
    	$re[]=M("App_member_account")->where(['member_id'=>$get_member['userId']])->setInc('account_type_'.$type,$money);	
    	//添加转账记录
    	$re[]=$this->addTransfer($user_id, $get_member['userId'], 1, "转账给".$get_member['loginName'],$money);
    	$re[]=$this->addTransfer($get_member['userId'], $user_id, 2, "收到转账".$pay_member['loginName'],$money);
    
    	//添加财务日志
    	$re[] = $finance->addFinance($user_id, 3, "转账给".$get_member['loginName'].$account_type_one['name']. $money, 2, $money, $type);
    	$re[] = $finance->addFinance($get_member['userId'], 3,  "收到".$pay_member['loginName']."转账".$account_type_one['name']. $money, 1, $money, $type);
		$re[] = $finance->addFinance($user_id, 6, "转账手续费", 2, $fee,$type);
//     	dump($re);
    	
    	if(in_array("false",$re)){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= 1;
    		$data['msg']= '转账成功';
    		return json($data);
    	}else{
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -1;
    		$data['msg']= '转账失败';
    		return json($data);
    	}    
    }
    /**
     *
     * 添加转账记录
     * @param int $member_id  用户id
     * @param int $receive_id  发送或者接受的id(也是用户的)
     * @param int $type   1为发送，2为接受
     * @param String $content 本次描述
     * @param int $money 本次转账金额
     * @return 成功返回true；失败返回false
     */
    public function addTransfer($member_id,$receive_id,$type,$content,$money){
    	$data['member_id']=$member_id;
    	$data['receive_id']=$receive_id;
    	$data['type']=$type;
    	$data['content']=$content;
    	$data['add_time']=time();
    	$data['status']=1;
    	$data['money']=$money;
    	$re=Db::name("App_transfer")->add($data);
    	if($re){
    		return true;
    	}else{
    		return false;
    	}
    }
    /**
     * 验证用户存不存在
     * email	用户名
     */
    public function checkout_user(){
    	$email = I('email');
    	$member = M('Users')->where(array('loginName'=>$email))->find();
    	if($member){
    		$data['data'] = array('user_id'=>$member['userId'],'token'=>'');
    		$data['code']= 1;
    		$data['msg']= '存在';
    		return json($data);
    		
    	}else{
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -1;
    		$data['msg']= '不存在';
    		return json($data);
    	}
    }
    
    
    /*
     判断是否可以转账
    参数 name string;
    */
    public function isTransfer(){
    	//查找可以转账积分
    	$account_type = Db::name('App_account_type')->field('id,name,transfer')->select();
    	if($account_type){
    		$data['data'] = array('account_type'=>$account_type);
    		$data['code']= 1;
    		$data['msg']= '成功';
    		return json($data);
    	}else{
    		$data['data'] = array('account_type'=>'');
    		$data['code']= -1;
    		$data['msg']= '没有可以转账积分';
    		return json($data);
    	}
    	 
    }
    /**
     * 付款（扫码）
     */
    public function payment(){
//     	return json(['data'=>'','code'=>-9,'msg'=>'该服务已暂停']);
    	//付款用户
    	$token1 = input('token1');
    	//收款用户
    	$token2 = input('token2');
    	$type = input('type');
    	$money = input('money');
    	$paypwd = input('paypwd');
    	if(empty($token1)){
    		return json(['data'=>'','code'=>-1,'msg'=>'无付款用户token']);
    	}
    	if(empty($token2)){
    		return json(['data'=>'','code'=>-2,'msg'=>'无收款用户token']);
    	}
    	//付款人信息
    	$uid1= db('token')->where(['token'=>$token1])->find()['uid'];
    	$uid2= db('token')->where(['token'=>$token2])->find()['uid'];
    	$user1 = Db::name('Users')->where(array('userId'=>$uid1))->find();
    	//收款人信息
    	$user2 = Db::name('Users')->where(array('userId'=>$uid2))->find();
    	//防止重复提交
    	$trade = Cache::get('tradeMoney_'.$uid1);
    	if($trade == true){
    		return json(['data'=>'','code'=>-1,'msg'=>'请勿频繁操作']);
    	}
    	//设置缓存
    	Cache::set('tradeMoney_'.$uid1,true,8);
    	if(empty($user1) || empty($user2)){
    		return json(['data'=>'','code'=>-6,'msg'=>'token未找到用户']);
    	}
    	if($money<1){
    		return json(['data'=>'','code'=>-3,'msg'=>'输入金额有问题']);
    	}
    	if(empty($paypwd)){
    		return json(['data'=>'','code'=>-4,'msg'=>'请填写交易密码']);
    	}
    	if(md5($paypwd) != $user1['payPwd']){
    		return json(['data'=>'','code'=>-5,'msg'=>'交易密码错误']);
    		
    	}
    	$finance = new \FinanceApi();
    	//判断金额
    	//	TODO
    	$one = M('app_member_account')->field('account_type_'.$type)->where(array('member_id'=>$uid1))->find();
    	$account_type_one = M('app_account_type')->where(array('id'=>$type))->find();//获取币种的信息
    	$limit_type = $account_type_one['limit_type'];
    	if($limit_type == 2){
    		$db = $finance->judgeNowMonthFinance();
    		$where['finance_type'] = 3;
    		$where['member_id'] = $uid1;
    		$old_money = DB::name($db)->where($where)->sum('money');
    		$all_money = $old_money +$money;
    	}else{
    		$all_money = $money;
    	}
    	//判断转账上限
    	$top = $account_type_one['limit_transfer_money'];
    	if($all_money > $top){
    		return json(['data'=>'','code'=>-6,'msg'=>"超出转账限额"]);
    	}
    	$bili = $account_type_one['transfer_fee_bili'];
    	$fee = $money*$bili*0.01;
    	$all_money = $money+$fee;
    	if($one['account_type_'.$type]<$all_money){
    		return json(['data'=>'','code'=>-6,'msg'=>$account_type_one['name']."不足"]);
    	}
    	//账户余额操作
    	$re[]=M("App_member_account")->where(['member_id'=>$uid1])->setDec('account_type_'.$type,$all_money);
    	$re[]=M("App_member_account")->where(['member_id'=>$uid2])->setInc('account_type_'.$type,$money);
    	
    	//添加财务日志
    	$re[] = $finance->addFinance($uid1, 3, "转账给".$user2['loginName'].$account_type_one['name']. $money, 2, $money, $type);
    	$re[] = $finance->addFinance($uid2, 3,  "收到".$user1['loginName']."转账".$account_type_one['name']. $money, 1, $money, $type);
    	$re[] = $finance->addFinance($uid1, 6, "转账手续费", 2, $fee,$type);
    	if($re){
    		return json(['data'=>'','code'=>1,'msg'=>'转账成功']);
    	}else{
    		return json(['data'=>'','code'=>-8,'msg'=>'网络异常']);
    	}
    }
    
    
    
    
    
    /**
     * 收款（扫码）
     * @return \think\response\Json
     */
    public function getment(){
//     	return json(['data'=>'','code'=>-9,'msg'=>'该服务已暂停']);
    	//收款用户
    	$token1 = input('token1');
    	//付款用户
    	$token2 = input('token2');
    	$type = input('type');
    	$money = (float)input('money');
    	
    	if(empty($token1)){
    		return json(['data'=>'','code'=>-1,'msg'=>'无收款用户token']);
    	}
    	if(empty($token2)){
    		return json(['data'=>'','code'=>-2,'msg'=>'无付款用户token']);
    	}
    	$uid1= db('token')->where(['token'=>$token1])->find()['uid'];
    	$uid2= db('token')->where(['token'=>$token2])->find()['uid'];
    	$user1 = db('users')->where(['userId'=>$uid1])->find();
    	$user2 = db('users')->where(['userId'=>$uid2])->find();
    	
    	$trade = Cache::get('tradeMoney_'.$uid1);
    	
    	if($trade == true){
    		return json(['data'=>'','code'=>-1,'msg'=>'请勿频繁操作']);
    	}
    	//设置缓存
    	Cache::set('tradeMoney_'.$uid1,true,8);
    	
    	//判断付款用户存在
    	if(!$user1){
    		return json(['data'=>'','code'=>-3,'msg'=>'收款用户不存在']);
    	}
    	//判断收款用户存在
    	if(!$user2){
    		return json(['data'=>'','code'=>-4,'msg'=>'付款用户不存在']);
    	}
    	//判断非负
    	if($money<=0){
    		return json(['data'=>'','code'=>-9,'msg'=>'支付金额不合理']);
    	}
    	
    	
    	//TODO
    	$finance = new \FinanceApi();
    	//付款用户
    	$one = M('app_member_account')->field('account_type_'.$type)->where(array('member_id'=>$uid2))->find();
    	$account_type_one = M('app_account_type')->where(array('id'=>$type))->find();//获取币种的信息
    	//判断转账上限
    	$limit_type = $account_type_one['limit_type'];
    	if($limit_type == 2){
    		$db = $finance->judgeNowMonthFinance();
    		$where['finance_type'] = 3;
    		$where['member_id'] = $uid2;
    		$old_money = DB::name($db)->where($where)->sum('money');
    		$all_money = $old_money +$money;
    	}else{
    		$all_money = $money;
    	}
    	//判断转账上限
    	$top = $account_type_one['limit_transfer_money'];
    	if($all_money > $top){
    		return json(['data'=>'','code'=>-6,'msg'=>"超出转账限额"]);
    	}
    	//账户信息
    	//获取要转账的币种的余额
    	//获取所有的币种余额
    	 
    	$bili = $account_type_one['transfer_fee_bili'];
    	$fee = $money*$bili*0.01;
    	$all_money = $money+$fee;
    	if($one['account_type_'.$type]<$all_money){
    		$data['data'] = array('user_id'=>'','token'=>'');
    		$data['code']= -6;
    		$data['msg']= $account_type_one['name']."不足";
    		return json($data);
    	}
    	//账户余额操作
    	$re[]=M("App_member_account")->where(['member_id'=>$uid2])->setDec('account_type_'.$type,$all_money);
    	$re[]=M("App_member_account")->where(['member_id'=>$uid1])->setInc('account_type_'.$type,$money);
    	//添加财务日志
    	$re[] = $finance->addFinance($uid2, 3, "转账给".$user1['loginName'].$account_type_one['name']. $money, 2, $money, $type);
    	$re[] = $finance->addFinance($uid1, 3,  "收到".$user2['loginName']."转账".$account_type_one['name']. $money, 1, $money, $type);
    	$re[] = $finance->addFinance($uid2, 6, "转账手续费", 2, $fee,$type);
    	if($re){
    		return json(['data'=>'','code'=>1,'msg'=>'转账成功']);
    	}else{
    		return json(['data'=>'','code'=>-8,'msg'=>'网络异常']);
    	}
    }
    /**
     * 付款页面提交判断
     */
    public function judgePay(){
    	$user_id = Base::$member['user_id'];
    	$password = input('paypwd');
    	$type = input('type');
    	$money = input('money');
    	$user = Db::name('Users')->where(array('userId'=>$user_id))->find();
    	//判断是否有支付密码
    	if(empty($password)){
    		return json(['data'=>'','code'=>-5,'msg'=>'请输入二级密码']);
    	}
    	//判断支付密码是否正确
    	if(md5($password)!=$user['payPwd']){
    		return json(['data'=>'','code'=>-6,'msg'=>'二级密码不正确']);
    	}
    	if($money<1){
    		return json(['data'=>'','code'=>-6,'msg'=>'请填写正确的金额']);
    	}
    	$member_account = Db::name('App_member_account')->where(array('member_id'=>$user_id))->find();
    	//获得本次转账需要的金额
    	$all = $this->getFeeByType($type, $money);
    	if($member_account['account_type_'.$type] < $all){
    		return json(['data'=>'','code'=>-1,'msg'=>'账号余额不足']);
    	}
    	return json(['data'=>'','code'=>1,'msg'=>'满足转账需求']);
    }

    /**
     * 通过积分种类  金额获得手续费
     * @param unknown $type
     * @param unknown $money
     */
    public function getFeeByType($type,$money){
    	$account_type = Db::name('App_account_type')->where(array('id'=>$type))->find();
    	$fee = $money*$account_type['transfer_fee_bili']*0.01;
    	$all = $money+$fee;
    	return $all;
    }
    
 
    /**
     * 积分之间相互转换
     */
    public function currency_conversion(){
    	$list = M('Account_type')->select();
    	foreach($list as $k=>$v){
    		if(!empty($list[$k]['conversion'])){
    			$conversion = explode(',', $list[$k]['conversion']);
    			$where['id'] = array('in',$conversion);
    			$arr = M('Account_type')->field('name,id')->where($where)->select();
    			foreach($arr as $m=>$n){
    				$bb['name'] =$list[$k]['name'].'转换'.$arr[$m]['name'];
    				$bb['id'] =$list[$k]['id'].'_'.$arr[$m]['id'];
    				$jifen = M('Member_account')->field('account_type_'.$list[$k]['id'])->where(array('member_id'=>$_SESSION['USER_KEY_ID']))->find();
    				$bb['first_jifen_name'] = $list[$k]['name'];
    				$bb['first_jifen_id'] = $list[$k]['id'];
    				$bb['first_jifen'] = $jifen['account_type_'.$list[$k]['id']];
    				$aa[] = $bb;
    			}
    		}
    	}
    	//转换记录
    	$where['member_id'] =$_SESSION['USER_KEY_ID'];
    	$where['type'] = 3;
    	$count =  M('Finance')->where($where)->count();
    	$Page   = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    	$show   = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    	$finance = M('Finance')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
    	// 		dump($finance);die();
    	$this->assign('finance',$finance);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->assign('aa',$aa);
    	$this->display();
    }
    /**
     * 会员转换积分方法实现
     */
    public function transformation_ok(){
    	$type=I('type',"");
    	$num=I("money","");
    	$password=I("password","");
    	if(empty($num)){
    		$msg['status']=-1;
    		$msg['info']="请填写转换金额";
    		$this->ajaxReturn($msg);exit();
    	}
    
    	if($num<0){
    		$msg['status']=-2;
    		$msg['info']="请输入正数";
    		$this->ajaxReturn($msg);exit;
    	}
    	//截取类型
    	$arr = explode('_',$type);
    	$one = M('Member_account')->field('account_type_'.$arr[0])->where(array('member_id'=>$_SESSION['USER_KEY_ID']))->find();
    	$two = M('Member_account')->field('account_type_'.$arr[1])->where(array('member_id'=>$_SESSION['USER_KEY_ID']))->find();
    	$account_type_one = M('Account_type')->where(array('id'=>$arr[0]))->find();
    	$account_type_two = M('Account_type')->where(array('id'=>$arr[1]))->find();
    	if($num>$one['account_type_'.$arr[0]]){
    		$msg['status']=-3;
    		$msg['info']='您的'.$account_type_one['name'].'不足';
    		$this->ajaxReturn($msg);exit;
    	}
    	if(empty($password)){
    		$msg['status']=-4;
    		$msg['info']="请输入交易密码";
    		$this->ajaxReturn($msg);exit;
    	}
    	if($this->member['pwdtrade'] != md5($password)){
    		$msg['status']=-5;
    		$msg['info']="交易密码错误，请重新输入";
    		$this->ajaxReturn($msg);exit;
    	}
    	$data['member_id']=$_SESSION['USER_KEY_ID'];
    	$data['num']=$num*(1);
    	$data['fee']=0.00;
    	$data['all_num']=$num;
    	$data['add_time']=time();
    	$data['type']=$type;
    	$data['status']=1;
    	M()->startTrans();
    	$re[]=M("Zhuanhuan")->add($data);//添加转账记录
    	//减钱加钱
    	$whereuser['member_id']=$_SESSION['USER_KEY_ID'];
    	$re[] =M('Member_account')->where($whereuser)->setDec('account_type_'.$account_type_one['id'],$num);
    	$y = $this->balance($_SESSION['USER_KEY_ID'],$account_type_one['id']);
    	$re[] =M('Member_account')->where($whereuser)->setInc('account_type_'.$account_type_two['id'],$num);
    	$re[] = $this->addFinance($_SESSION['USER_KEY_ID'],3,$account_type_one['name']."转换".$account_type_two['name'],$num,'','2',$y);
    	if(in_array("false", $re)){
    		M()->rollback();
    		$msg['status']=1;
    		$msg['info']="转换失败";
    		$this->ajaxReturn($msg);exit();
    	}else{
    		M()->commit();
    		$msg['status']=-6;
    		$msg['info']="转化成功";
    		$this->ajaxReturn($msg);exit();
    	}
    }
    
    
    
    /**
     * 获取用户的余额（多币种）
     * @return Ambigous <\think\response\Json, \think\Response, \think\response\View, \think\response\Xml, \think\response\Redirect, \think\response\Jsonp, unknown, \think\Response>
     */
    public function getUserBalance(){
    	$user_id = Base::$member['user_id'];
    	$type = intval(input('type'));//获取币种
    	if(!is_int($type) || $type > 4){
    		$data['data'] = array('balance'=>'');
    		$data['code']= -2;
    		$data['msg']= '参数错误';
    		return json($data);
    	}
    	$one = M('app_member_account')->field('account_type_'.$type)->where(array('member_id'=>$user_id))->find();
    	$list = db('App_account_type')->where(array('id'=>$type))->find();
    	$fee = $list['transfer_fee_bili'];
    	$zhuan_ed = $list['limit_transfer_money'];
    	$limit_type = $list['limit_type'];
    	if($one){
    		$data['data'] = array('balance'=>$one['account_type_'.$type],'fee'=>$fee,'zhuan_ed'=>$zhuan_ed,'limit_type'=>$limit_type);
    		$data['code']= 1;
    		$data['msg']= '成功';
    		return json($data);
    	}else{
    		$data['data'] = array('balance'=>'','fee'=>$fee,'zhuan_ed'=>$zhuan_ed,'limit_type'=>$limit_type);
    		$data['code']= -1;
    		$data['msg']= '失败';
    		return json($data);
    	}
    	
    	
    }
    
    /**
     * 通过token获取真实姓名
     * @return Ambigous <\think\response\Json, \think\Response, \think\response\View, \think\response\Xml, \think\response\Redirect, \think\response\Jsonp, unknown, \think\Response>
     */
    public function getUserName(){
    	$user_id = Base::$member['user_id'];
    	$list = db('App_member_relation')->where(array('member_id'=>$user_id))->find();
    	
    	if($list){
    		$data['data'] = array('name'=>$list['name'],pic=>$list['pic']);
    		$data['code']= 1;
    		$data['msg']= '成功';
    		return json($data);
    	}else{
    		$data['data'] = array('name'=>'',pic=>'');
    		$data['code']= -1;
    		$data['msg']= '失败';
    		return json($data);
    	}
    }
    /**
     * 根据积分种类获得积分信息
     */
    public function getTopAndBili(){
    	$id = input('id');
    	$account_type = Db::name('App_account_type')->where(array('id'=>$id))->find();
    	if($account_type['limit_type'] == 2){
    		$pre = '每日';
    	}else{
    		$pre = '单笔';
    	}
    	$list['content'] = $pre.'最高限额'.$account_type['limit_transfer_money'];
    	$list['bili'] = $account_type['transfer_fee_bili'];
    	
    	$data['data'] = $list;
    	$data['code']= 1;
    	$data['msg']= '成功';
    	return json($data);
    }
 
    
}